package org.wesc.boot.service.system.user;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wesc.boot.common.utils.HttpContextUtil;
import org.wesc.boot.common.utils.IpUtil;
import org.wesc.boot.dao.entity.LoginLog;
import org.wesc.boot.dao.entity.User;
import org.wesc.boot.dao.mapper.LoginLogMapper;
import org.wesc.boot.dao.mapper.UserMapper;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 用户登录时相关的服务
 *
 * @author Wesley Cheung
 */
@Service
public class UserLoginService implements Serializable {

    private UserMapper userMapper;

    private LoginLogMapper loginLogMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setLoginLogMapper(LoginLogMapper loginLogMapper) {
        this.loginLogMapper = loginLogMapper;
    }

    /**
     * 更新用户登录时间
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserLoginTime(User user) {
        user.setLastLoginTime(LocalDateTime.now());
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(User.USER_ID, user.getUserId());
        userMapper.update(user, updateWrapper);
    }

    /**
     * 存储用户登录记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveUserLoginLog(User user) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(user.getUserId());
        loginLog.setUserName(user.getUserName());
        loginLog.setLoginTime(LocalDateTime.now());
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        String ip = IpUtil.getIpAddr(request);
        loginLog.setIp(ip);
        loginLog.setLocation(null);
        loginLog.setDevice(null);

        loginLogMapper.insert(loginLog);
    }

}
